package com.zelin.gulimall.product.web;


import com.zelin.gulimall.product.entity.CategoryEntity;
import com.zelin.gulimall.product.service.CategoryService;
import com.zelin.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by WF on 2021/1/10 19:21
 */
@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //1.查询首页
    @GetMapping({"/","/index.html"})
    public String index(Model model){
        //1.1)查询一级分类
        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categorys();
        //System.out.println("categoryEntityList = " + categoryEntityList);
        //1.2)将一级分类放到model中
        model.addAttribute("categorys",categoryEntityList);
        return "index";
    }

    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCategoryJson(){
        Map<String, List<Catelog2Vo>> categoryJson = categoryService.getCategoryJson();
        return categoryJson;
    }

    @GetMapping("hello")
    @ResponseBody
    public String hello(){
        RLock lock = redissonClient.getLock("my-lock");
        //lock.lock();//默认30s到期，到达30的1/3时间即10s就会自动续期
        lock.lock(10, TimeUnit.SECONDS); //默认到达指定时间后不会自动续期，这个时间一般设置成比业务处理时间长（最佳方案）
        try {
            System.out.println("加锁成功，正在执行业务。。。" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
            System.out.println("解锁成功。。。" + Thread.currentThread().getId());
        }
        return "hello";
    }

    /**
     * 读写锁---》读锁操作
     * @return
     */
    @ResponseBody
    @GetMapping("/read")
    public String readLock(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock(); //获取读锁
        String s = "";
        try {
            rLock.lock(10,TimeUnit.SECONDS);
            System.out.println("读锁加锁成功~~~~");
            //从redis中读取数据
            s = redisTemplate.opsForValue().get("writeValue");
            System.out.println("读取到数据：" + s);

        } catch (Exception e) {

        }finally {
            System.out.println("读锁解锁成功！");
            rLock.unlock();     //解除读锁
        }
        return s;
    }
    /**
     * 读写锁---》写锁操作
     * 测试：可以在redis中定义一个writeValue字段，值为任意，如：111，这样可以测试
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public String writeLock(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock(); //获取写锁
        String s = "";
        try {
            rLock.lock(10,TimeUnit.SECONDS);
            System.out.println("写锁加锁成功~~~~");
            //写uuid到redis中
            s = UUID.randomUUID().toString();
            Thread.sleep(20000);
            redisTemplate.opsForValue().set("writeValue",s);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println("写锁解锁成功！");
            rLock.unlock();     //解除写锁
        }
        return s;
    }

    /**
     * 车库停车，3车位（此时可以在redis中定义一个park，值为3进行测试）
     * 信息量:可以做分布式限流
     * @return
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        //park.acquire(); //获取一个值，占一个车位，这个方法是阻塞式获取，获取不到会一直在这里等
        boolean b = park.tryAcquire(); //这个方法是非阻塞式获取，(偿试获取)获取到了就返回true,否则，返回false

            return "ok"+b;

    }
    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();     //释放一个车位

        return "ok";

    }

    /**
     * 闭锁，比如：以学校锁大门为例，例如：有5个班的学生，只有5个班的学生都走完了，才能锁门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch lockDoor = redissonClient.getCountDownLatch("lockDoor");
        lockDoor.trySetCount(5);    //设置5个班级
        lockDoor.await();             //等待闭锁都完成
        return "放假了。。。";
    }

    @GetMapping("/gogo/{id}")
    @ResponseBody
    public String gogo(@PathVariable int id) throws InterruptedException {
        RCountDownLatch lockDoor = redissonClient.getCountDownLatch("lockDoor");
        lockDoor.countDown();       //计数器减1，就是将上面的班级数减1
        return id + "班的人走了。。。";
    }
}
